/**
 * Created by shenc on 2015/12/8.
 */

//右侧浮动导航
$(window).on('scroll', function () {
    var scrollTop = $(document).scrollTop();
    var rightBar = $('#rightBar');

    if (scrollTop >= 150) {
        rightBar.addClass('fix-bar');
    } else {
        rightBar.removeClass('fix-bar');
    }
});

//缩略图滚动
var scroll = new lrScroll({
    auto: false,
    autoHideNav: false,
    spacing: 4,				//单位间距
    obj: '#thumbScroll',		//滚动对象
    sNum: '1'			    //滚动单位个数
});

//图片放大镜效果
$(".jqzoom").jqueryzoom({xzoom: 400, yzoom: 400});

//鼠标经过切换预览图片函数
function preview(img) {
    var showImg = $("#preview").find('img'),
        jqImg = $(img);
    showImg.attr("src", jqImg.data("mimg"));
    showImg.attr("jqimg", jqImg.data("bimg"));
    jqImg.closest('li').addClass('cur').siblings('li').removeClass('cur');
}

//地址
$.ajax({
    url: '/area',
    type: 'get',
    dataType: 'json',
    success: function (res) {
        //TODO 转换对
        iplocation = [];//{name: "北京", id: "1", c: 72}
        provinceCityJson = {};

        var level2 = [], level3 = [], level4 = [], provinceIds = [], cityIds = [];

        //第1级数据
        for (var i = 0; i < res.length; i++) {
            var curData = res[i];

            if (curData.parent_code * 1 == 0) {

                iplocation.push({id: curData.code, name: curData.name});

                //为生成provinceCityJson做准备
                provinceIds.push(curData.code);
                provinceCityJson[curData.code] = [];

            } else {
                level2.push(curData);
            }

        }

        //第2级数据
        for (var j = 0; j < level2.length; j++) {
            var curDataTwo = level2[j];

            if ($.inArray(curDataTwo.parent_code, provinceIds) != -1) {
                //为生成provinceCityJson做准备
                cityIds.push(curDataTwo.code);

                provinceCityJson[curDataTwo.code] = [];
                provinceCityJson[curDataTwo.parent_code].push({id: curDataTwo.code, name: curDataTwo.name});
            } else {
                level3.push(curDataTwo);
            }
        }

        //第3级数据
        for (var k = 0; k < level3.length; k++) {
            var curDataThree = level3[k];
            if ($.inArray(curDataThree.parent_code, cityIds) != -1) {
                provinceCityJson[curDataThree.parent_code].push({id: curDataThree.code, name: curDataThree.name});
            } else {
                level4.push(curDataThree);
            }
        }

        provinceCityJson.p = iplocation;

        //tools.log('iplocation',iplocation);
        //tools.log('provinceCityJson',provinceCityJson);
        //tools.log('错误',level4.length);

        //实例化地区插件
        $('.address-plugin').Address({proid: 0, cityid: 0, areaid: 0});

    }
});

//邮费切换
$('.store-selector').find('input').on('input', function () {
    var numItem = $('.js-expressPrice'), input = $(this), id = input.val();
    var ids = id.split(',');
    //获取运费信息
    if (ids.length) {
        if (ids[0] == 650000 || ids[0] == 540000) {
            numItem.text(15);
        } else {
            numItem.text(7);
        }
    }


});

var numTools = $('.num-tool');
var addCartBtn = $('.js-addCart');
var allCartItem = $('.js-cart').find('.cart-num');
var cartItem = $('#js-cart');
var payBtn = $('.js-payBtn');
var payTip = $('.js-payTip');

//修改数量
numTools.each(function () {
    numPlugin($(this), function (val, numInput) {
        //todo E贸易 非单个商品超过1000元 禁止购买
        var goodsType = numInput.data('type'),
            goodsPrice = numInput.data('price');

        //如果是普通商品
        if (goodsType == 0) return false;

        //如果是E贸易商品
        if (goodsType == 1) {
            var moreThan = val > 1 && goodsPrice * val > 1000;
            payBtn.toggleClass('disabled', moreThan).prop('disabled', moreThan);//支付按钮状态修改
            moreThan ? payTip.show() : payTip.hide();//提示显示隐藏
        }

    });
});

//加入购物车
addCartBtn.on('click', function (e) {
    var num = numTools.find('.num-input').val();

    var that = $(this),
        fromOffset = that.offset(),
        toOffset = cartItem.offset();

    if (that.hasClass('disabled')) return false;

    var id = that.data('id'), oldVal = cartItem.find('.cart-num').text();
    var flyItem = $('<img id="fly" class="fly-img" src="' + $("#preview").find('img').attr('src') + '" alt="">');

    $.ajax({
        url: page_global.addCart_url,
        type: 'post',
        dataType: 'json',
        data: {goods_id: id, goods_num: num},
        success: function (res) {
            if (res.message == '' && res.goods_num != ''){
                allCartItem.text(res.goods_num);
            } else {
                layer.msg('已加入购物车', {icon: 1, offset: '10px'})
            }
        }
    });
    flyItem.fly({
        start: {
            left: e.pageX,  //开始位置（必填）#fly元素会被设置成position: fixed
            top: fromOffset.top - $(window).scrollTop() - 20  //开始位置（必填）
        },
        end: {
            left: toOffset.left, //结束位置（必填）
            top: toOffset.top - $(window).scrollTop() + 100,  //结束位置（必填）
            width: 20, //结束时高度
            height: 20 //结束时高度
        },
        speed: 1.3, //越大越快，默认1.2
        vertex_Rtop: 10, //运动轨迹最高点top值，默认20
        onEnd: function () {
            flyItem.remove();
            //allCartItem.text(oldVal*1+num*1);
        } //结束回调
    });

});

//立即购买
payBtn.on('click', function () {
    if (payBtn.hasClass('disabled')) return false;

    var id = payBtn.data('id'),
        num = numTools.find('.num-input').val() || 1;

    if (page_global.check_url) {
        $.ajax({
            url: page_global.check_url,
            type: 'post',
            dataType: 'json',
            data: {cartGoods: [{goods_id: id, buy_num: num}]},
            success: function (res) {
                tools.log(res);
                if (res.status == 'error') {
                    layer.msg('请求出错，请刷新页面后重试', {
                        offset: '10px'
                    });
                    return;
                }
                if (res.status == 'success') {
                    window.location.href = page_global.fastPay_url;
                }
            }
        });
    }
});

//返回顶部
$('.js-goTop').on('click', function () {
    tools.goToY(0, 300, function () {
    });
    return false;
});


//点击评论数显示评论
$('.js-linkToComment').on('click',function(){
    $('.js-loadComment').click();
    //滚动到评论顶部
    setTimeout(function(){
        var offset=$('.js-filter').offset();
        tools.goToY(offset.top,300);
    },100);
});

//切换到评论时自动加载第一个分类----只执行一次
$('.js-loadComment').on('click',function(){
    var autoLoad=$('.js-autoLoad');

    autoLoad.removeClass('js-autoLoad');
    autoLoad.trigger('click');
});

var jqP = $('.js-commentList');
var config = {
    getUrl: '/goods/comment',
    tpl: $('#commentTpl').html(),
    pageSize: 2,
    goodsId: jqP.attr('data-id')
};

//实例化评论插件
var makeComment = new MakeCommentList(jqP, config);

function MakeCommentList(jqP, opts) {
    var def = {
        getUrl: '',
        tpl: '',
        pageSize: 3,
        goodsId: ''
    };

    var This = this;

    this.opts = $.extend(true, {}, def, opts || {});
    this.jqP = jqP;
    this.filterWrap = jqP.find('.js-filter');
    this.listWrap = jqP.find('.js-comList');
    this.pageWrap = jqP.find('.js-pager');

    this.type = 'all';
    this.totalPage = 0;
    this.curPage = 1;

    //切换 全部 好评 中评 差评
    this.filterWrap.on('click', '.js-type', function (e) {
        var that = $(this),label=$(this).closest('label');

        if((label.hasClass('cur')&&label.hasClass('js-autoLoad'))||that.prop('disabled')) return false;

        label.addClass('cur').siblings('label').removeClass('cur');
        This.type = that.data('type');
        This.curPage = 1;
        This.listWrap.find('li').remove();

        //加载评论数据
        This.getData();
    });

    //获取评论数据
    this.getData = function () {
        var opts = This.opts;

        //显示加载中
        var loadingHtml='<li><div class="bl-nodata"><div class="nodata-txt"><img class="fn-mr6" style="margin-top: 2px;" src="../images/loading-1.gif" alt="">评论加载中... </div></div></li>';
        This.listWrap.append(loadingHtml);

        $.ajax({
            url: opts.getUrl,
            type: 'post',
            dataType: 'json',
            data: {goods_id: This.opts.goodsId, condition: This.type,page:This.curPage},
            success: function (res) {

                if(res.status==0){
                    //暂无评价
                }else{
                    This.rendering(res.comments);
                }
            }
        });
    };

    //渲染评论列表
    this.rendering = function (commens) {
        var newHtmls=[],comsData={},starHtml,picHtml=[];

        //删除老评论
        This.listWrap.find('li').remove();

        for(var i=0;i<commens.data.length;i++){
            comsData=commens.data[i];
            starHtml=[];
            picHtml=[];

            //处理评分
            for(var j=0;j<comsData.star;j++){
                starHtml.push('<span class="on"><a class="score-icon"><i></i></a></span>');
            }

            //处理图片
            if(comsData.picture&&comsData.picture.length){
                var pictures=comsData.picture;
                for(var k=0;k<pictures.length;k++){
                    var curPic=pictures[k];
                    picHtml.push('<li><img class="thumb" data-big="'+curPic[1]+'" src="'+curPic[0]+'" alt=""></li>');
                }
            }

            //处理匿名
            //if(comsData.type==1){
            //    comsData.phone=comsData.phone.length<5?(comsData.phone.slice(0,2)+'***'):(comsData.phone.slice(0,3)+'***'+comsData.phone.slice(-4));
            //}
            comsData.user_name=comsData.phone.length<5?'匿名评论':(comsData.phone.slice(0,3)+'***'+comsData.phone.slice(-4));

            comsData.star=starHtml.join('');
            comsData.pictureHtml=picHtml.join('');

            var html = tools.htmlTemplate(This.opts.tpl, comsData,true);
            tools.log('html',html);
            newHtmls.push(html);
        }

        if (newHtmls.length) {
            This.listWrap.append(newHtmls.join(''));

            This.curPage=commens.current_page;
            This.pager(commens.last_page);
            This.bind();
        }else{
            var noData='<li><div class="bl-nodata"><div class="nodata-txt">暂无评论</div></div></li>';
            This.listWrap.append(noData);
            This.pager(1);
        }


        //滚动到评论顶部
        var offset=This.filterWrap.offset();
        tools.goToY(offset.top,300);


    };

    //生成分页
    this.pager = function (pageNum) {
        var pageHtml = [];
        var prev, next;
        if (This.curPage == 1) {
            prev = '<li class="disabled"><span>«</span></li>';
        } else {
            prev = '<li><a href="javascript:;" data-page="' + (This.curPage - 1) + '">«</a></li>';
        }
        if (This.curPage == pageNum) {
            next = '<li class="disabled"><span>»</span></li>';
        } else {
            next = '<li><a href="javascript:;" data-page="' + (This.curPage + 1) + '">»</a></li>';
        }

        pageHtml.push(prev);

        for (var i = 1; i < pageNum + 1; i++) {
            var curLi = '';

            if (i == This.curPage) {
                curLi = '<li class="active"><span>' + i + '</span></li>';
            } else {
                curLi = '<li><a href="javascript:;" data-page="' + i + '">' + i + '</a></li>';
            }
            pageHtml.push(curLi);
        }

        pageHtml.push(next);
        if (pageHtml.length > 3) {
            This.pageWrap.html(pageHtml.join('')).closest('.pager').show();
        } else {
            This.pageWrap.closest('.pager').hide();
        }

    };

    //绑定评论列表内部事件
    this.bind = function () {

        //换页
        this.pageWrap.off('click').on('click','a',function(){
            var pageNum=$(this).data('page');

            if(This.curPage==pageNum) return false;
            This.curPage=pageNum;
            This.getData();
        }).on('click','.prev',function(){
            if($(this).hasClass('disabled')||This.curPage<=1) return false;
            This.curPage--;
            This.getData();
        }).on('click','.next',function(){
            if($(this).hasClass('disabled')||This.curPage>=This.totalPage) return false;
            This.curPage++;
            This.getData();
        });

        //评论图片预览
        $('.js-picPreview',This.listWrap).on('click', '.thumb', function () {
            var that = $(this),
                li = that.closest('li'),
                jqP = that.closest('.js-picPreview'),
                previewBox = jqP.find('.preview-box'),
                curSrc = that.data('big');

            li.addClass('cur').siblings('li').removeClass('cur');
            previewBox.find('img').attr('src', curSrc);
            previewBox.show();

        }).on('click', '.close', function () {
            $(this).closest('.preview-box').hide().end().closest('.js-picPreview').find('.cur').removeClass('cur');
        });
    };

    return {};
}
